package com.usian.controller;

import com.usian.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RequestMapping("/user")
@RestController
public class ConsumerController {

    //从Nacos注册中心获取服务端的ip、端口、要调用的服务
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //访问Rest服务的客户端  原生的服务调用
    @Autowired
    private RestTemplate restTemplate;

    //访问测试路径
    //http://localhost:8002/user/findUserById?userId=10

    //@RequestMapping(value = "consumer/user/{userId}",method = RequestMethod.GET)
    @RequestMapping("findUserById")
    public User findUserById(Integer userId){

        //找到服务提供者的服务
        ServiceInstance lbc = loadBalancerClient.choose("nacos-provider");
        //拼接请求地址
        String url = "http://"+lbc.getHost()+":"+lbc.getPort()+"/user/findUserById/"+userId;
        //发送请求
        return restTemplate.getForObject(url,User.class);
    }

}
